#!/bin/bash
expire_date=2
sleep_sec=8
CURL_CMD="curl -s --connect-timeout 5  --max-time 20 "

cache_home="/data/proxy_cache_dir"
temp_home="/data/proxy_temp_dir"
vod_file_home="/data/proxy_vod_dir/vod"
f4m_file_home="/data/proxy_f4m_dir"
m3u8_file_home="/data/proxy_m3u8_dir"

hostbase="http://127.0.0.1"
parse_hostbase="http://127.0.0.1:8383"
m3u8_proxy_hostbase="http://127.0.0.1:8484"
arg_manifest="$1"


if [ $# -lt 1 ] ; then
   echo "Usage: liverobot.sh /cuclive/livestream/manifest.f4m"
   echo "       liverobot.sh http://l2.cuctv.com/cuclive/livestream/manifest.f4m"
   exit 1
fi


livepath="/cuclive/livestream"
f4m="manifest.f4m"
m3u8="playlist.m3u8"

if [ "${arg_manifest:0:5}" = "http:" ] ; then
first_slash=`awk -v "STR=${arg_manifest:7}" -v "SUB=/" '{print index(STR,SUB) +7 -1}' <<< "" `
last_slash=`expr "$arg_manifest" : ".*/" - length "/" `
len=`expr $last_slash - $first_slash`
livepath="${arg_manifest:first_slash:len}"
elif [ "${arg_manifest:0:1}" = "/" ] ; then
last_slash=`expr "$arg_manifest" : ".*/" - length "/" `
livepath="${arg_manifest:0:$last_slash}"
fi

echo $livepath $f4m $m3u8

if [ ! -e $cache_home ] ; then
   mkdir -p $cache_home
   chown -R nobody:nobody $cache_home
   chmod -R 777 $cache_home
fi

if [ ! -e $temp_home ] ; then
   mkdir -p $temp_home
   chown -R nobody:nobody $temp_home
   chmod -R 777 $temp_home
fi

if [ ! -e $vod_file_home$livepath ] ; then
   mkdir -p $vod_file_home$livepath
   chown -R nobody:nobody ${vod_file_home:0:19}
fi

if [ ! -e "$f4m_file_home$livepath" ] ; then
   mkdir -p  "$f4m_file_home$livepath"
   chown -R nobody:nobody $f4m_file_home
fi

if [ ! -e "$m3u8_file_home$livepath" ] ; then
   mkdir -p  "$m3u8_file_home$livepath"
   chown -R nobody:nobody $m3u8_file_home
fi



manifest_file="$f4m_file_home$livepath/$f4m"
m3u8_file="$m3u8_file_home$livepath/$m3u8"

vod_manifest_file="$vod_file_home$livepath/$f4m"
vod_m3u8_file="$vod_file_home$livepath/$m3u8"



urlbase="$hostbase$livepath"
parse_urlbase="$parse_hostbase$livepath"
m3u8_proxy_urlbase="$m3u8_proxy_hostbase$livepath"

url_f4m="$urlbase/$f4m"
url_m3u8="$urlbase/$m3u8"
proxy_url_m3u8="$m3u8_proxy_urlbase/$m3u8"

echo "starting `date +"%F %T"`"

#http://192.168.233.128/cuclive/livestream/media_b125000_w2091662836.abst/Seg1-Frag19126
notexists_cnt=10
while [ ! -e $manifest_file  -o ! -e $m3u8_file  ]
do
  echo "the file $manifest_file or $m3u8_file is not exists, just get it and sleep 1s $url_f4m and $proxy_url_m3u8";
  $CURL_CMD $url_f4m
  $CURL_CMD $proxy_url_m3u8  -o  $m3u8_file
  sleep 1
  notexists_cnt=`expr $notexists_cnt - 1`
  if [ $notexists_cnt -lt 1 ] ; then
     if [ ! -e $vod_file_home$livepath ] ; then
        mkdir -p $vod_file_home$livepath
        chown -R nobody:nobody ${vod_file_home:0:19}
     fi
     
     if [ ! -e "$f4m_file_home$livepath" ] ; then
        mkdir -p  "$f4m_file_home$livepath"
        chown -R nobody:nobody $f4m_file_home
     fi
     
     if [ ! -e "$m3u8_file_home$livepath" ] ; then
        mkdir -p  "$m3u8_file_home$livepath"
        chown -R nobody:nobody $m3u8_file_home
     fi
     notexists_cnt=10
     echo "download the url $url_f4m or $proxy_url_m3u8 exceel max cnt($notexists_cnt) sleep 10s";
     sleep 10
  fi
done


if [ ! -e $vod_manifest_file ] ; then
  ln -sf  $manifest_file  $vod_manifest_file
fi

playlist=`cat  $manifest_file    |  grep "bootstrapInfo"  | awk   -F\"  '{print $4}'`
medialist=`cat $manifest_file    |  grep "<media"         | awk   -F\"  '{print $2}'`
url_playlist="$parse_urlbase/$playlist"
url_medialist="$urlbase/$medialist"
local_media_file="$vod_file_home$livepath/$medialist"
echo $url_playlist $url_medialist $local_media_file

if [ ! -e $local_media_file ] ; then
  mkdir -p $local_media_file
fi

frags=`$CURL_CMD "$url_playlist"`
echo $frags

if [ "$frags" != "repeated" -a "$frags" != "error" ] ; then
  echo "todownload segs"
  f=`echo $frags | sed  's/,/ /g'`
  for i in  $f ; do
    u="$url_medialist""Seg1-Frag"$i
    l="$local_media_file""Seg1-Frag"$i
    if [ ! -e $l ] ; then
      echo "download $u >> $l "
      $CURL_CMD $u  -o  $l
    else
      echo "has downloaded $u -> $l exists" 
    fi
  done 
fi


m3u8_sessionid=`cat  $m3u8_file  |  grep "wowzasessionid" | awk   -F=   '{print $2}' | awk   -F\&   '{print $1}'`
m3u8_playlist_url="$proxy_url_m3u8?wowzasessionid=$m3u8_sessionid"

notexists_cnt=10
while [ ! -e $vod_m3u8_file ]
do
  $CURL_CMD $m3u8_playlist_url  -o  $vod_m3u8_file 
  sleep 1
  notexists_cnt=`expr $notexists_cnt - 1`
  if [ $notexists_cnt -lt 1 ] ; then
    notexists_cnt=10
    echo "download the file $m3u8_playlist_url exceel max cnt($notexists_cnt) sleep 10s";
    sleep 10
    break
  fi
done

echo $m3u8_sessionid $m3u8_playlist_url $vod_m3u8_file
frags=`$CURL_CMD  "$m3u8_playlist_url" | grep "media_"`
EXTINF=`$CURL_CMD "$m3u8_playlist_url" | grep "#EXTINF"`

#OLD_IFS="$IFS" 
#IFS="," 
ARR_EXTINF=($EXTINF) 
#IFS="$OLD_IFS" 

old_max_frags_str=`cat $vod_m3u8_file  | grep "media_" | tail -1`
old_max_frags_len=`expr "$old_max_frags_str" : ".*\." - length "."`
#old_max_frags=${old_max_frags_str:6:(old_max_frags_len-6)}
#old_EXTINF=`cat $vod_m3u8_file | grep "#EXTINF"`
echo $frags $EXTINF


idx=0
local_media_file="$vod_file_home$livepath"
if [ "$frags" != "" ] ; then
  echo "todownload segs"
  for i in  $frags ; do
    u="$urlbase/"$i
    len=`expr  "$i" : ".*?" - length "?"`
    l="$local_media_file/"${i:0:len}
    if [ ! -e $l ] ; then
      echo "download $u >> $l"
      $CURL_CMD $u  -o  $l
      cur_frags_len=`expr "$i" : ".*\." - length "."`
      if [ ${i:6:(cur_frags_len-6)} -gt ${old_max_frags_str:6:(old_max_frags_len-6)} ] ; then
        echo "has new ts ${i:6:(cur_frags_len-6)} ${old_max_frags_str:6:(old_max_frags_len-6)}  idx:$idx  ${ARR_EXTINF[$idx]}"
        echo "${ARR_EXTINF[$idx]}" >>  $vod_m3u8_file 
        echo "$i" >>  $vod_m3u8_file 
      fi
    else
      echo "has downloaded $u -> $l exists" 
    fi
    idx=`expr $idx + 1`
  done 
fi


echo "delete expired file (exceed $expire_date date)"
find  "$local_media_file/" -type f -ctime +$expire_date ! -name "*.f4m" 
find  "$local_media_file/" -type f -ctime +$expire_date ! -name "*.f4m" -exec rm -rf   {} \; 
echo "end `date +"%F %T"`"

cmd=$0
p=${cmd:0:1}
if [ "$p" = "." ] ; then
  curpath=`pwd`
  echo "$curpath/${cmd:2} sleep $sleep_sec(s)"
  echo  -e "\n\n\n\n"
  sleep $sleep_sec
  exec $curpath/${cmd:2} $*
#elif [ "$p" = "/" ] ; then
else
  echo "$0 sleep $sleep_sec(s)"
  echo  -e "\n\n\n\n"
  sleep $sleep_sec
  exec $0 $*
fi
